<template>
  <div class="node">
    <div class="pTitle" :class="nodeIndex === treeIndex ? 'active_title' : 'pTitle'">
      <div class="label" @click="caret(node, false)"
        :class="node.children && node.children.length ? 'pLabel' : 'cLabel'">
        <div class="labelText">{{ node.label }}</div>
        <div class="el-icon" @click.stop="caret(node, true)" title="展开/收起" v-if="node.children && node.children.length">
          <i v-show="showChild" class="el-icon-caret-bottom"></i>
          <i v-show="!showChild" class="el-icon-caret-top"></i>
        </div>
      </div>
    </div>
    <div class="child" :class="showChild ? 'caretChild' : ''" v-if="node.children && node.children.length">
      <tree-node :treeIndex="treeIndex" @setChooseIndex="setChooseIndex" @getTreeNode="getTreeNode"
        v-for="child, index in node.children" :key="index" :node="child"
        :nodeIndex="`${nodeIndex}-${index}`"></tree-node>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TreeNode',
  props: {
    node: {
      type: Object,
      required: true,
    },
    nodeIndex: {
      type: Number,
      required: false,
    },
    treeIndex: {
      type: String,
      required: false,
    }
  },
  data() {
    return {
      showChild: false
    }
  },
  mounted() {
  },
  methods: {
    caret(node, falg) {
      if (falg) {
        this.showChild = !this.showChild;
      }
      this.getTreeNode(node);
      this.setChooseIndex(this.nodeIndex);
    },
    getTreeNode(node) {
      this.$emit('getTreeNode', node)
    },
    setChooseIndex(index) {
      this.$emit('setChooseIndex', index)
    }
  }
};
</script>

<style lang="scss" scoped>
.node {
  width: 100%;

  .pTitle {
    .label {
      height: 36px;
      line-height: 34px;
      border-bottom: 1px solid #B8BCC3;
      position: relative;
      cursor: pointer;

      &:hover {
        background: #6176D0;
        color: #ffffff;

        .el-icon {
          color: #ffffff;
        }
      }

      .labelText {
        width: 100%;
        text-align: center;
      }

      .el-icon {
        width: 30px;
        text-align: right;
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        color: #7E9AB5;
      }
    }

    .pLabel {
      background-color: #EBEFFF;
    }

    .cLabel {
      background-color: transparent;
    }
  }

  .active_title {
    .label {
      background-color: #6176D0;
      color: #ffffff;
      .el-icon {
        color: #ffffff;
      }
    }
  }

  .child {
    height: 0;
    overflow: hidden;
    transition: all 0.3s;
  }

  .caretChild {
    height: auto;
  }
}
</style>